import { BaseCommand } from '../../core/command.js';
import type { CommandContext } from '../../types/index.js';
import { ApifoxGenerator } from './generator.js';
import path from 'path';
import fs from 'fs-extra';

export class ApifoxCommand extends BaseCommand {
  name = 'apifox';
  description = 'Generate TypeScript API files from Apifox documentation';

  options = [
    {
      name: 'debug',
      description: 'Enable debug mode',
      type: 'boolean' as const,
      default: false,
    },
    {
      name: 'path',
      description: 'Target path for generated files',
      type: 'string' as const,
      default: './src/api',
    },
  ];

  examples = [
    'genwavejs apifox -p ./src/api/sale',
    'genwavejs apifox --debug --path ./src/api/user',
  ];

  async execute(context: CommandContext): Promise<void> {
    const { debug, path: targetPathOption } = context.options;
    const { logger } = context;

    try {
      logger.info('Starting Apifox API generation...');
      
      const targetPath = path.resolve(process.cwd(), targetPathOption as string);
      const configPath = path.join(targetPath, 'api.config.json');
      
      // 检查配置文件是否存在
      if (!fs.existsSync(configPath)) {
        logger.error(`Configuration file not found: ${configPath}`);
        logger.info('Please create api.config.json with the following structure:');
        logger.info(`{
  "docsUrl": "http://127.0.0.1:4523/export/openapi?projectId=4749955&version=3.0",
  "includeTags": ["商品管理"],
  "excludeTags": ["分类管理"],
  "requestInstance": "@/utils/http/request"
}`);
        throw new Error('Configuration file not found');
      }
      
      // 读取配置文件
      const config = await fs.readJson(configPath);
      
      // 验证配置
      if (!config.docsUrl) {
        logger.error('docsUrl is required in api.config.json');
        throw new Error('Invalid configuration: docsUrl is required');
      }
      
      if (!config.includeTags || !Array.isArray(config.includeTags)) {
        logger.error('includeTags array is required in api.config.json');
        throw new Error('Invalid configuration: includeTags array is required');
      }
      
      // 创建生成器实例
      const generator = new ApifoxGenerator(config, targetPath, debug as boolean);
      
      // 生成API文件
      await generator.generate();
      
      logger.success('API files generated successfully!');
      
    } catch (error) {
      logger.error('Failed to generate API files:', error);
      throw error;
    }
  }
}
